package iPersistence.sqlSession;


import iPersistence.pojo.Configuration;
import iPersistence.pojo.MappedStatement;

import java.beans.IntrospectionException;
import java.lang.reflect.*;
import java.sql.SQLException;
import java.util.List;

/**
 * @author Feuler
 * @since 2020/11/6
 **/

public class DefaultSqlSession implements SqlSession {

    private final Configuration configuration;

    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public <E> List<E> selectList(String statementId, Object... params) throws SQLException, IllegalAccessException, IntrospectionException, InstantiationException, NoSuchFieldException, NoSuchMethodException, InvocationTargetException, ClassNotFoundException {
        // 调用SimpleExecutor的query方法
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
        List<E> result = simpleExecutor.query(configuration, mappedStatement, params);
        return result;
    }

    @Override
    public <T> T selectOne(String statementId, Object... params) throws SQLException, IllegalAccessException, InvocationTargetException, IntrospectionException, InstantiationException, ClassNotFoundException, NoSuchMethodException, NoSuchFieldException {
        List<Object> objects = selectList(statementId, params);
        if (objects.size() == 1) {
            return (T) objects.get(0);
        } else {
            throw new RuntimeException("查询结果为空或返回结果过多");
        }
    }

    @Override
    public void update() {

    }

    @Override
    public void delete() {

    }

    @Override
    public <T> T getMapper(Class<?> mapperClass) {
        // 使用JDK动态代理为DAO接口生成代理对象并返回
        Object proxyInstance = Proxy.newProxyInstance(DefaultSqlSession.class.getClassLoader(), new Class[]{mapperClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
                // 准备参数 statementId=接口全限定名.方法名
                String className = method.getDeclaringClass().getName();
                String methodName = method.getName();
                String statementId = className + "." + methodName;

                // 获取返回值类型
                Type genericReturnType = method.getGenericReturnType();
                // 判断是否进行了参数类型参数化
                if (genericReturnType instanceof ParameterizedType) {
                    return selectList(statementId, objects);
                }
                return selectOne(statementId, objects);
            }
        });

        return (T) proxyInstance;
    }
}
